#!/usr/bin/env node

/* MODULE IMPORTS */
const dbName = 'website.db';
const Koa = require('koa');
const staticDir = require('koa-static');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const views = require('koa-views');

const userSession = require('./lib/userSessionUnit');

const accountRouter = require('./apis/account');
const fileRouter = require('./apis/file');
const indexRouter = require('./apis/index.api');
const mainRouter = require('./apis/main.api');
const suggestRouter = require('./apis/suggest.api');

const defaultPort = 8080;
const port = process.env.PORT || defaultPort;


const app = new Koa();

/* CONFIGURING THE MIDDLEWARE */
app.keys = ['darkSecret'];
app.use(bodyParser());
app.use(session(app));

if (process.argv.indexOf('--production') > 1) {
    console.log('This is production');
    app.use(views(`${__dirname}/koa-dist-views`, { extension: 'handlebars' }, { map: { handlebars: 'handlebars' } }));
}
else {
    app.use(views(`${__dirname}/views`, { extension: 'handlebars' }, { map: { handlebars: 'handlebars' } }));
}
app.use(staticDir('public'));


// auth middle
app.use(async (ctx, next) => {
    var requestPath = ctx.request.path.toLocaleLowerCase();

    var whiteArr = ['^/register$','^/login$','^/logout$','^/file/upload$','^$','^/$','^/index/.*$'];

    for(var i=0;i<whiteArr.length;i++){
        let item = whiteArr[i];
        if(new RegExp(item).test(requestPath)){
            await next();
            return;
        }
    }

    if(!userSession.isLogin(ctx)){
        return ctx.redirect('/login?msg=you need to log in')
    } else {
        await next();
    }
});

app.use(indexRouter.routes());
app.use(accountRouter.routes());
app.use(fileRouter.routes());
app.use(mainRouter.routes());
app.use(suggestRouter.routes());



module.exports = app.listen(port, async() => console.log(`listening on port ${port}`))